package com.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.common.to.UserRegTo;
import com.common.utils.R;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.vo.UserRegVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-21 10:20
 */
@Controller
public class RegisterController {
    @Resource
    private MemberFeignService memberFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public String register(@Valid UserRegVo userRegVo ,   // redirectAttributes：相当于重定向的Model.addAttribute
                           BindingResult bindingResult, RedirectAttributes redirectAttributes){
        // 检查参数是否正确
        Map<String, String> errorMap = new HashMap<>();
        if(bindingResult.hasErrors()){
            errorMap = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errorMap);    // 原理是将数据保存在cookie里重定向
            return "redirect:http://auth.gulimall.com/reg.html";        // 重定向防止刷新页面多次提交
        }
        // 检查验证码是否正确
        String sessionCode = userRegVo.getSessionCode();
        if(sessionCode.contains("date")){
            // 加入点击刷新功能，所以这里传来的数据也携带了date，需要在存储和判断时进行切割：1689356906date=1619082685478date=1619082686637date=1619082698581
            sessionCode.substring(0,sessionCode.indexOf("date"));
        }
        String value = stringRedisTemplate.opsForValue().get(sessionCode);
        if(StringUtils.isEmpty(value)){
            // 如果验证码为空说明验证码过期
            errorMap.put("code","验证码已过期，请刷新后重试");
            redirectAttributes.addFlashAttribute("errors",errorMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }else{
            if(!value.equals(userRegVo.getCode())){
                errorMap.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errorMap);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            UserRegTo userRegTo = new UserRegTo();
            BeanUtils.copyProperties(userRegVo, userRegTo);
            R r = memberFeignService.register(userRegTo);
            // 如果调用结果不为0，说明发生异常
            if(r.getCode() != 0){
                errorMap.put("msg",r.getData("msg",new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors",errorMap);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            // 正常，跳转到登陆页面
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
